<?php
namespace Feima\FlightLogProxy;

use Feima\FlightLogProxy\DatabaseMaintainer as DatabaseMaintainer;
/**
 * Created by PhpStorm.
 * User: jimmy
 * Date: 2017/12/13
 * Time: 下午2:53
 */
class FlightMonitorLogProxy{

    private $maintainer;
    private $isUseSourceDb;
    /**
     * FlightMonitorLogProxy constructor.
     * @param $maintainer
     */
    public function __construct($config)
    {
        $this->maintainer = new DatabaseMaintainer($config);
        $this->isUseSourceDb=$this->maintainer->getConfig()["is_use_souce_db"];
    }

    public function begin($created_at){

        $curYear=date('Y',$created_at);
        $dbProxy=$this->getDbProxy($curYear);
        if($dbProxy){
            $dbProxy->begin();
        }
    }
    public function commit($created_at){
        $curYear=date('Y',$created_at);
        $dbProxy=$this->getDbProxy($curYear);
        if($dbProxy){
            $dbProxy->commit();
        }
    }



    /**
     * @param $local_id 管家本地GUID标志
     * @param $message  消息内容
     * @param $flight_mission_id 任务ID
     * @param $created_at 管家创建时间
     * @return bool
     */
    public function insert($local_id,$message,$flight_mission_id,$created_at){
        if($created_at){
            $curYear=date('Y',strtotime($created_at));
            $dbProxy=$this->getDbProxy($curYear);
            $tableName=DatabaseMaintainer::getTableName();
            if($dbProxy){
                return
                    $dbProxy->execute("INSERT INTO $tableName (local_id, message,flight_mission_id,created_at,created_str) SELECT
	'$local_id',
	'$message',
	$flight_mission_id,
	'$created_at',
	'$created_at'
FROM
	DUAL
WHERE
	NOT EXISTS (
		SELECT
			local_id
		FROM
			$tableName
		WHERE
			local_id = '$local_id'
	)");
            }
        }
        return false;

    }

    public function count($where,$unixTime){
        $tableName=DatabaseMaintainer::getTableName();
        $sql="select count(*) as total from $tableName where $where ";
        $record=$this->fetchAllWithSql($sql,$unixTime);
        $total=0;
        for($i=0;$i<count($record);$i++){
            $total+=intval($record[$i]["total"]);
        }
        return $total;
    }
    /**
     * @param $where 查询条件 可包含order 条件
     * @param null $unixTime 日志存储时间（以飞机创建时间为主），传入时间有助于快速查询
     * @return null
     */
    public function fetchAll($where,$unixTime=null){
        if(!empty($where)){
            $tableName=DatabaseMaintainer::getTableName();
            $sql="select * from $tableName where $where ";
            return $this->fetchAllWithSql($sql,$unixTime);
        }
        return false;
    }


    public function fetchAllWithSql($sql,$unixTime=null)
    {
        if (!empty($sql)) {
            if ($unixTime != null) {
                $year = date('Y', $unixTime);
                $days = date('z', $unixTime);
                //如果是接近年末或者年初
                //需要偏移一年的数据库来查询
                $paddingYear = 0;
                if ($days == 1) {
                    //需要查询上一年的
                    $paddingYear = $year - 1;
                }
                if ($days == 365) {
                    $paddingYear = $year + 1;
                }
                $startYear = $this->maintainer->getConfig()["target_database_start_year"];
                if ($year >= $startYear) {
                    $tempData = $this->maintainer->getYearDbProxy($year)->fetchAll($sql);
                    if ($paddingYear != 0 && $paddingYear >= $startYear) {
                        $paddingData = $this->maintainer->getYearDbProxy($paddingYear)->fetchAll($sql);
                        if ($paddingData) {
                            if ($tempData) {
                                array_merge($paddingData, $tempData);
                            } else {
                                return $paddingData;
                            }
                        }
                    } else {
                        FLOG("偏移查询年份小于开始年份");
                    }
                } else {
                    FLOG("查询年份小于开始年份");
                }
                $tempData = $this->mergeSourceDbData($tempData, $sql);
                return $tempData;
            } else {
                //所有连接都查询
                $curYear = date('Y');
                $startYear = $this->maintainer->getConfig()["target_database_start_year"];
                $resultArray = array();
                for (; $startYear <= $curYear; $startYear++) {
                    $tempData = $this->maintainer->getYearDbProxy($startYear)->fetchAll($sql);
                    if ($tempData) {
                        if ($resultArray) {
                            $resultArray = array_merge($resultArray, $tempData);
                        } else {
                            $resultArray = $tempData;
                        }
                    }
                }
                $resultArray = $this->mergeSourceDbData($resultArray, $sql);
                return $resultArray;
            }
        }
        return false;
    }

    public function getDbProxy($year){
        if($year>0){
            return $this->maintainer->getYearDbProxy($year);
        }
    }

    /**
     * 合并源数据库的
     * @param $resultArray
     * @param $sql
     * @return array
     */
    private function mergeSourceDbData($resultArray,$sql){
        if($this->isUseSourceDb){
            $tempData=$this->maintainer->getSourceDbProxy()->fetchAll($sql);
            if($tempData){
                $resultArray=array_merge($resultArray,$tempData);
            }
        }
        return $resultArray;
    }
}
